<template>
	<div class="padding20">
		<div class="left">
			<el-divider content-position="left">审批内容</el-divider>
			<iframe v-show="isIframeLoaded" ref="previewPage" class="result-wrapper" frameborder="0" :src="iframePath" @load="iframeLoad" />
			<div v-show="!isIframeLoaded" v-loading="true" class="result-wrapper"></div>
			<div>
				<el-divider content-position="left">审批意见</el-divider>
				<el-form ref="approveForm" :model="approveForm" :rules="approveRules">
					<el-form-item label="审批结果" :label-width="formLabelWidth" prop="approveStatus">
						<fortress-radio-group v-model="approveForm.approveStatus" :dictList="approveStatusList" placeholder="请选择" clearable></fortress-radio-group>
					</el-form-item>
					<el-form-item label="审批意见" :label-width="formLabelWidth" prop="approveOpinion">
						<el-input v-model="approveForm.approveOpinion" type="textarea" :rows="3" placeholder="请输入审批意见"></el-input>
					</el-form-item>
					<el-form-item label="审批意见图片" :label-width="formLabelWidth">
						<picture-upload type="picture-card" v-model="approveForm.image" :limit="9" :fixed="false"></picture-upload>
					</el-form-item>
					<el-form-item label="审批意见文件" :label-width="formLabelWidth">
						<fortress-upload type="file" :formData="approveForm" name="file" :limit="9" multiple></fortress-upload>
					</el-form-item>
				</el-form>
				<!--  todo 需要完善自选抄送人选择和展示  -->
				<template v-if="approveForm.csType == '01'">
					<el-divider content-position="left">自选抄送人</el-divider>
					<el-form label-width="110px">
						<el-form-item label="自选抄送人">
							<v-auditer v-model="selected" disDept authFlag="00" @on-confirm="onAuditerConfirm">
								<template #default="{list, open}">
									<div class="s-auditer" @click="open"></div>
									<el-table :data="list" border>
										<el-table-column label="名字" prop="name"></el-table-column>
									</el-table>
								</template>
							</v-auditer>
						</el-form-item>
					</el-form>
				</template>
				<div slot="footer" class="footer">
					<el-button @click="$router.go(-1)" size="medium" type="danger">取 消</el-button>
					<el-button :loading="submitLoading" style="margin-left: 0;" type="primary" size="medium" @click="submitForm('approveForm')">
						确 定
					</el-button>
					<v-appoint
						@on-success="
							() => {
								init($route.query.tid, $route.query.id)
								csOpt($route.query.tid, $route.query.id, approveForm.task)
							}
						"
					></v-appoint>
					<v-auditer v-model="selected" :multiple="false" disDept authFlag="00" @on-confirm="onTransfer">
						<template #default="{list, open}">
							<el-button type="warning" size="medium" @click="open">转办</el-button>
						</template>
					</v-auditer>
					<backToDom ref="backToDom"></backToDom>
					<el-button size="medium" type="danger" @click="onTheEnd">结束流程</el-button>
				</div>
			</div>
		</div>

		<div class="right">
			<self-appoint ref="SelfAppoint" v-model="params" :actKey="$route.query.actKey" :pid="$route.query.pid" :engineVersion="$route.query.engineVersion" readonly request></self-appoint>
		</div>
	</div>
</template>

<script>
import { exportDefault } from "@/components/fortress-approve-draggable/utils/index"
import { makeUpHtml } from "@/components/fortress-approve-draggable/generator/html"
import { makeUpJs } from "@/components/fortress-approve-draggable/generator/datajs"
import { makeUpCss } from "@/components/fortress-approve-draggable/generator/css"
import { formconfigInfo } from "@/api/flowable/formconfig.js"
import { csOptional, completeTask } from "@/api/approves/approves.js"
import { parse } from "@babel/parser"
import vAppoint from "./components/appoint.vue"
import backToDom from "./components/backToDom.vue"
import pictureUpload from "@/components/fortress-upload/picture-upload.vue"
import request from "@/common/request"

const editorObj = {
	html: null,
	js: null,
	css: null,
}
export default {
	data() {
		return {
			formLabelWidth: "120px",
			visible: false,
			isIframeLoaded: false,
			isInitcode: false, // 保证open后两个异步只执行一次runcode
			isRefreshCode: false, // 每次打开都需要重新刷新代码
			htmlCode: "",
			jsCode: "",
			cssCode: "",
			params: {},
			formData: {},
			selected: {
				dept: [],
				user: [],
			},
			generateConf: { type: "file" },
			formConfigData: {
				id: "",
				designContent: "",
				tbContent: "",
				viewContent: "",
			},
			form: {},
			rowId: "",
			iframePath: process.env.NODE_ENV === "production" ? "/admin/preview.html?disabled=" : "/preview.html?disabled=",
			approveForm: {
				tid: "",
				id: "",
				task: "",
				approveStatus: "",
				approveOpinion: "",
				csType: "00", // 00 不允许指定抄送人 01 允许指定抄送人
				csAppointName: "",
				csAppointValue: "",
				image: "",
				file: "",
			},
			approveStatusList: [
				{
					name: "同意",
					code: "1",
				},
				{
					name: "不同意",
					code: "2",
				},
			],
			approveRules: {
				approveStatus: [{ required: true, message: "请选择审核意见", trigger: "blur" }],
			},
			sysUserId: "",
			// couldBack: false,
			submitLoading: false,
		}
	},
	async created() {
		let _this = this
		let tid = this.$route.query.tid || ""
		let id = this.$route.query.id || ""
		this.approveForm.task = this.$route.query.task || ""
		this.$nextTick(() => {
			this.$refs.SelfAppoint.getData()
		})
		this.init(tid, id)
		this.csOpt(tid, id, this.approveForm.task)
		window.dataeditfinish = function() {
			_this.$message({
				type: "success",
				message: "操作成功!",
			})
			_this.$emit("refreshData")
			_this.closeHandler()
		}

		// const result = await request("post", "/flowable/approves/refuseBackInfo", {
		// 	...this.$route.query,
		// })
		// this.couldBack = result.data === "ANY_NODE"
	},
	computed: {},
	watch: {},
	methods: {
		async onTransfer(_value, [user]) {
			try {
				await request("post", "/flowable/approves/turnTask", {
					...this.$route.query,
					turnUser: user.id,
				})
				this.$message.success("转办成功")

				this.init(this.$route.query.tid, this.$route.query.id)
				this.csOpt(this.$route.query.tid, this.$route.query.id, this.approveForm.task)
			} catch (error) {
				this.$message.error("转办失败")
			}
		},
		onAuditerConfirm(_value, list) {
			console.log(_value, list)
		},
		init(tbId, id) {
			this.approveForm.tid = tbId
			this.approveForm.id = id
			;(this.formConfigData.id = tbId + ""),
				(this.rowId = id),
				formconfigInfo(tbId).then(resp => {
					if (resp.code == 0) {
						if (resp.data.viewContent) {
							this.visible = true
							this.formData = JSON.parse(resp.data.viewContent)
							this.formData.formBtns = false
							this.formData.disabled = true
							this.onOpen()
						} else {
							this.drawingList = []
						}
					}
				})
		},
		onOpen() {
			const { type } = this.generateConf
			this.htmlCode = makeUpHtml(this.formData, type)
			this.jsCode = makeUpJs(this.formData, type, this.formConfigData.id, this.rowId)
			this.cssCode = makeUpCss(this.formData)
			this.setEditorValue("editorHtml", "html", this.htmlCode)
			this.setEditorValue("editorJs", "js", this.jsCode)
			this.setEditorValue("editorCss", "css", this.cssCode)
			this.runCode()
		},
		setEditorValue(id, type, codeStr) {
			editorObj[type] = codeStr
		},
		runCode() {
			const jsCodeStr = editorObj.js
			try {
				const ast = parse(jsCodeStr, { sourceType: "module" })
				const astBody = ast.program.body
				if (astBody.length > 1) {
					this.$confirm("js格式不能识别，仅支持修改export default的对象内容", "提示", {
						type: "warning",
					})
					return
				}
				if (astBody[0].type === "ExportDefaultDeclaration") {
					const postData = {
						type: "refreshFrame",
						data: {
							generateConf: this.generateConf,
							html: this.htmlCode,
							js: jsCodeStr.replace(exportDefault, ""),
							css: this.cssCode,
							scripts: [],
							links: [],
						},
					}
					let _this = this
					let timer = setInterval(function() {
						if (_this.$refs.previewPage) {
							_this.isIframeLoaded = true
							_this.$refs.previewPage.contentWindow.postMessage(postData, location.origin)
							clearInterval(timer)
						}
					}, 50)
				} else {
					this.$message.error("请使用export default")
				}
			} catch (err) {
				// this.$message.error(`js错误：${err}`)
				console.error(err)
			}
		},
		iframeLoad() {
			// if (!this.isInitcode) {
			//   this.isIframeLoaded = true
			//   this.isRefreshCode && (this.isInitcode = true) && this.runCode()
			// }
			this.runCode()
		},
		//关闭
		closeHandler() {
			this.rowId = ""
			this.visible = false
			this.isIframeLoaded = false
			this.isInitcode = false // 保证open后两个异步只执行一次runcode
			this.isRefreshCode = false // 每次打开都需要重新刷新代码
		},
		//提交表单数据
		submitForm() {
			this.$refs["approveForm"].validate(valid => {
				if (valid) {
					if (this.submitLoading) return
					this.submitLoading = true
					const data = {
						...this.approveForm,
						file: Array.isArray(this.approveForm.file) ? JSON.stringify(this.approveForm.file) : this.approveForm.file,
					}
					if (this.approveForm.csType == "01") {
						const list = (this.sysUserId || []).split(",")
						data.csAppointValue = this.selected.user.filter(item => !list.includes(item)).join()
					}
					completeTask(data)
						.then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})

								// if (this.approveForm.approveStatus == 2) {
								// 	this.$refs.backToDom.autoSubmitLast()
								// }

								this.$nextTick(() => {
									this.$router.go(-1)
								})
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
						.finally(() => {
							this.submitLoading = false
						})
				} else {
					console.log("error submit!!")
					return false
				}
			})
		},
		//查询该审批人是否能自选抄送人
		csOpt(tid, id, taskId) {
			let _this = this
			let queryParam = {}
			queryParam.tid = tid
			queryParam.id = id
			queryParam.taskId = taskId
			csOptional(queryParam).then(resp => {
				if (resp.code == 0) {
					//自定义抄送人
					if (resp.data.csType == "01") {
						_this.approveForm.csType = "01" // 00 不允许指定抄送人 01 允许指定抄送人
						_this.approveForm.csAppointName = resp.data.thisNodeAppoint
						_this.sysUserId = resp.data.sysUserId
						return
					}
				}
			})
		},

		async onTheEnd() {
			try {
				await this.$confirm("是否结束流程?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
			} catch (error) {
				return
			}

			try {
				await request("post", "/flowable/approves/endTask", {
					...this.$route.query,
				})
				this.$message.success("结束流程成功")

				// this.init(this.$route.query.tid, this.$route.query.id)
				// this.csOpt(this.$route.query.tid, this.$route.query.id, this.approveForm.task)
				this.$router.go(-1)
			} catch (error) {
				this.$message.error("结束流程失败")
			}
		},
	},
	components: {
		vAppoint,
		pictureUpload,
		backToDom,
	},
}
</script>

<style lang="scss" scoped>
@import "@/components/fortress-approve-draggable/styles/index";
@import "@/components/fortress-approve-draggable/styles/home";
.padding20 {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	gap: 20px;
	.left {
		flex: 1;
	}
	.right {
		flex: none;
		width: 450px;
	}
}
.result-wrapper {
	height: 40vh;
	overflow-y: auto;
	width: 100%;
	overflow: auto;
	padding: 12px;
	box-sizing: border-box;
}

.s-auditer {
	width: 40px;
	height: 40px;
	border-radius: 10px;
	position: relative;
	background: #ddd;
	cursor: pointer;
	margin-bottom: 15px;
	&::before,
	&::after {
		content: "";
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
		margin: auto;
		width: 2px;
		height: 20px;
		background: #fff;
	}
	&::before {
		transform: rotate(90deg);
	}
}

.footer {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	gap: 10px;
}
</style>
